﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace ElsProp.Model
{
    /// <summary>
    /// 
    /// </summary>
    public class FristWindowModel : ObservableObject
    {
        /// <summary>
        /// 加载装备
        /// </summary>
        public ICommand LoadZhuangBei { get; set; }
        /// <summary>
        /// 装备列表
        /// </summary>
        private List<PropModel> _propModels;
        /// <summary>
        /// 装备列表
        /// </summary>
        public List<PropModel> propModels { get => _propModels; set => SetProperty(ref _propModels, value); }
        /// <summary>
        /// 选择的装备列表
        /// </summary>
        private ObservableCollection<PropModel> _selectpropModels;
        /// <summary>
        /// 选择的装备列表
        /// </summary>
        public ObservableCollection<PropModel> selectpropModels { get => _selectpropModels; set => SetProperty(ref _selectpropModels, value); }
        /// <summary>
        /// 查询的属性值
        /// </summary>
        private string _selectpropModelsvalue;
        /// <summary>
        /// 查询的属性值
        /// </summary>
        public string selectpropModelsvalue
        {
            get => _selectpropModelsvalue;
            set
            {
                SetProperty(ref _selectpropModelsvalue, value);
                SelectPro();
            }

        }
        /// <summary>
        /// 属性
        /// </summary>
        private string _shuxingvalue;
        /// <summary>
        /// 属性
        /// </summary>
        public string shuxingvalue { get => _shuxingvalue; set => SetProperty(ref _shuxingvalue, value); }

        /// <summary>
        /// 选择的生效套装
        /// </summary>
        private ObservableCollection<SelectSuit> _selectSuitItem;
        /// <summary>
        /// 选择的生效套装
        /// </summary>
        public ObservableCollection<SelectSuit> selectSuitItem { get => _selectSuitItem; set => SetProperty(ref _selectSuitItem, value); }

        /// <summary>
        /// 
        /// </summary>
        public FristWindowModel()
        {
            LoadZhuangBei = new RelayCommand(LoadZhuangBeiMethod);
            selectSuitItem = new ObservableCollection<SelectSuit>();
            selectpropModels= new ObservableCollection<PropModel>();
            LoadZhuangBeiMethod();
            selectpropModelsvalue = "";
        }
        private IWorkbook GetWrokBooK(string filePath)
        {
            IWorkbook result = null;
            FileStream fileStream = null;
            try
            {
                using (fileStream = File.OpenRead(filePath))
                {
                    if (filePath.IndexOf(".xlsx", StringComparison.Ordinal) > 0)
                    {
                        result = new XSSFWorkbook((Stream)fileStream);
                    }
                    else if (filePath.IndexOf(".xls", StringComparison.Ordinal) > 0)
                    {
                        result = new HSSFWorkbook(fileStream);
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                fileStream?.Close();
                throw ex;
            }
        }
        private static DataTable GetSheetDt(ISheet isheet, int fixedRowCount = 1)
        {
            if (isheet == null)
            {
                return new DataTable();
            }

            DataTable dataTable = new DataTable
            {
                TableName = isheet.SheetName
            };
            int lastRowNum = isheet.LastRowNum;
            if (lastRowNum > 0)
            {
                IRow row = isheet.GetRow(0);
                if (row == null)
                {
                    return dataTable;
                }

                int lastCellNum = row.LastCellNum;
                if (fixedRowCount > 0)
                {
                    for (int i = row.FirstCellNum; i < lastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);
                        DataColumn column;
                        if (!string.IsNullOrWhiteSpace(cell?.StringCellValue))
                        {
                            column = new DataColumn(cell.StringCellValue);
                            dataTable.Columns.Add(column);
                            continue;
                        }

                        column = new DataColumn($"BlankRow{i}");
                        dataTable.Columns.Add(column);
                    }
                }
                else
                {
                    for (int j = row.FirstCellNum; j < lastCellNum; j++)
                    {
                        DataColumn column = new DataColumn("column" + (j + 1));
                        dataTable.Columns.Add(column);
                    }
                }

                for (int k = fixedRowCount; k <= lastRowNum; k++)
                {
                    IRow row2 = isheet.GetRow(k);
                    if (row2 == null)
                    {
                        continue;
                    }

                    DataRow dataRow = dataTable.NewRow();
                    for (int l = row2.FirstCellNum; l < lastCellNum; l++)
                    {
                        ICell cell = row2.GetCell(l);
                        if (cell == null)
                        {
                            if (l > 0)
                            {
                                dataRow[l] = "";
                            }
                        }
                        else
                        {
                            dataRow[l] = CellTypeValueFormat(cell);
                        }
                    }

                    dataTable.Rows.Add(dataRow);
                }
            }

            return dataTable;
        }
        private static object CellTypeValueFormat(ICell cell)
        {
            object result = null;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    result = "";
                    break;
                case CellType.Numeric:
                    {
                        short dataFormat = cell.CellStyle.DataFormat;
                        result = ((dataFormat != 14 && dataFormat != 31 && dataFormat != 57 && dataFormat != 58) ? ((object)cell.NumericCellValue) : ((object)cell.DateCellValue));
                        break;
                    }
                case CellType.String:
                    result = cell.StringCellValue;
                    break;
                case CellType.Boolean:
                    result = cell.BooleanCellValue;
                    break;
            }

            return result;
        }
        public Dictionary<string, DataTable> ExcelToDataTables(string filePath, int startSheetIndex = 0, int fixedRowCount = 1)
        {
            Dictionary<string, DataTable> dictionary = new Dictionary<string, DataTable>();
            try
            {
                IWorkbook wrokBooK = GetWrokBooK(filePath);
                if (wrokBooK != null)
                {
                    int numberOfSheets = wrokBooK.NumberOfSheets;
                    if (startSheetIndex > numberOfSheets)
                    {
                        throw new Exception("指定起始表索引大于表单数量！");
                    }

                    for (int i = startSheetIndex; i < numberOfSheets; i++)
                    {
                        dictionary.Add(wrokBooK.GetSheetName(i), GetSheetDt(wrokBooK.GetSheetAt(i), fixedRowCount));
                    }
                }

                return dictionary;
            }
            catch (Exception innerException)
            {
                throw new Exception("操作失败！", innerException);
            }
        }
        private void LoadZhuangBeiMethod()
        {
            string path = "FileData";
            List<PropModel> propModels = new List<PropModel>();
            if (!Directory.Exists(Data.path))
            {
                Directory.CreateDirectory(Data.path);
            }
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var files = Directory.GetFiles(Data.path);
            foreach (var file in files)
            {
                var zhuangbei = File.ReadAllText(file);
                try
                {
                    propModels.AddRange(Newtonsoft.Json.JsonConvert.DeserializeObject<SuitPropModel>(zhuangbei).PropModels);

                }
                catch
                {

                }
            }
            files = Directory.GetFiles(path);
            foreach (var file in files)
            {
                try
                {
                    var zhuangbei = GetWrokBooK(file);
                    foreach (var propModel in zhuangbei)
                    {
                        if (propModel != null)
                        {
                            List<string> cells = new List<string>();
                            List<int> danjian = new List<int>();
                            List<int> taozhuang = new List<int>();

                            int rowindex = 0;
                            int rowlosecount = 0;
                            while (rowlosecount < 3)
                            {
                                PropModel propModel1 = new PropModel();
                                propModel1.guid = Guid.NewGuid().ToString();
                                propModel1.Properties = new();
                                propModel1.SuitProperties = new();
                                var row = propModel.GetRow(rowindex);
                                if (row != null)
                                {
                                    bool celllose = true;
                                    int celindex = 0;
                                    while (celllose)
                                    {
                                        var cell = row.GetCell(celindex);
                                        if (cell != null)
                                        {
                                            var colname = cell.StringCellValue;
                                            if (rowindex == 0)
                                            {
                                                if (colname == "套装")
                                                {
                                                    taozhuang.Add(celindex);
                                                }
                                                if (colname == "单件")
                                                {
                                                    danjian.Add(celindex);
                                                }
                                            }
                                            else if (rowindex == 1)
                                            {
                                                if (!string.IsNullOrEmpty(colname))
                                                {
                                                    cells.Add(colname);
                                                }
                                                else
                                                {
                                                    cells.Add("");
                                                }
                                            }
                                            else
                                            {
                                                if (celindex == 0)
                                                {
                                                    propModel1.Suit = colname;
                                                }
                                                if (celindex == 1)
                                                {
                                                    Enum.TryParse<EnumZhuangBeiLan>(colname, out EnumZhuangBeiLan lan);
                                                    propModel1.BuWei = lan;
                                                }
                                                if (celindex == 2)
                                                {
                                                    propModel1.Name = colname;
                                                }
                                                if (danjian.Contains(celindex))
                                                {
                                                    if (!string.IsNullOrEmpty(colname) && colname != "0")
                                                    {
                                                        propModel1.Properties.Add(new ItemProperties()
                                                        {
                                                            PropertiesName = cells[celindex],
                                                            PropertiesValue = colname,
                                                        });
                                                    }

                                                }
                                                if (taozhuang.Contains(celindex))
                                                {
                                                    var data = colname.Split(',');
                                                    if (data.Length == 2)
                                                    {
                                                        int con = 0;
                                                        int.TryParse(data[0], out con);
                                                        propModel1.Properties.Add(new ItemProperties()
                                                        {
                                                            PropertiesName = cells[celindex],
                                                            PropertiesValue = data[1],
                                                            Condition = con
                                                        });
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            celllose = false;
                                        }
                                        celindex++;
                                    }
                                }
                                else
                                {
                                    rowlosecount++;
                                }
                                if (rowindex != 0 && rowindex != 1)
                                {
                                    if (propModel1.Properties.Count == 0 && propModel1.SuitProperties.Count == 0)
                                    {

                                    }
                                    else
                                    {
                                        propModels.Add(propModel1);
                                    }

                                }
                                rowindex++;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                }
            }
            foreach (var propModel in Data.propModels)
            {
                var has = propModels.Find(x => x.Suit == propModel.Suit && x.Name == propModel.Name);
                if (has == null)
                {
                    propModels.Add(propModel);
                }
            }
            foreach (var item in propModels)
            {
                if (item.SuitProperties == null || item.SuitProperties.Count == 0)
                {
                    var onesuit = propModels.FindAll(x => x.Suit == item.Suit && x.SuitName == item.SuitName);
                    foreach (var items in onesuit)
                    {
                        if (items != null && items.SuitProperties != null && items.SuitProperties.Count != 0)
                        {
                            item.SuitProperties = items.SuitProperties;
                            break;
                        }
                    }
                }
            }
            this.propModels = propModels;
            selectpropModels.Clear();
            foreach (var propModel in propModels)
            {
                propModel.SubPropertiesStr();
                selectpropModels.Add(propModel);
            }
            SelectSuit_SelectChage();
        }

        public void SelectPro()
        {
            if (string.IsNullOrEmpty(selectpropModelsvalue))
            {
                selectpropModels.Clear();
                foreach (var propModel in propModels)
                {
                    propModel.SubPropertiesStr();
                    selectpropModels.Add(propModel);
                }
                return;
            }
            if (selectpropModelsvalue.Trim() == "")
            {
                selectpropModels.Clear();
                foreach (var propModel in propModels)
                {
                    propModel.SubPropertiesStr();
                    selectpropModels.Add(propModel);
                }
                return;
            }
            var dst = propModels.FindAll(x => x.Suit.Contains(selectpropModelsvalue));
            var dst2 = propModels.FindAll(x => x.Name.Contains(selectpropModelsvalue));
            dst.AddRange(dst2);
            var gdart = dst.GroupBy(x => x.Name);
            List<PropModel> dst3 = new List<PropModel>();
            foreach (var gd in gdart)
            {
                dst3.Add(gd.First());
            }
            selectpropModels.Clear();
            foreach (var propModel in dst3)
            {
                propModel.SubPropertiesStr();
                selectpropModels.Add(propModel);
            }
        }


        public void SubSuit(List<PropModel> props)
        {
            if (selectSuitItem == null)
            {
                return;
            }
            var olddata = selectSuitItem.ToList();
            selectSuitItem.Clear();
            var suitgroup = props.GroupBy(x => x.Suit);
            foreach (var item in suitgroup)
            {
                var group = item.GroupBy(x => x.SuitName);
                foreach (var g in group)
                {
                    SelectSuit selectSuit = new SelectSuit()
                    {
                        suit = g.First().Suit,
                        suitItem = g.Key,
                        select = true,

                    };
                    selectSuit.SelectChage += SelectSuit_SelectChage;
                    var od = olddata.Find(x => x.suitItem == selectSuit.suitItem);
                    if (od != null)
                    {
                        selectSuit.select = od.select;
                    }
                    selectSuitItem.Add(selectSuit);
                }
            }
            propsLog = props;
            shuxingvalue = MyHelp.SubPropModel(props, selectSuitItem);
        }
        List<PropModel> propsLog { get; set; }
        private void SelectSuit_SelectChage()
        {
            if (propsLog == null || propsLog.Count == 0)
            {
                return;
            }
            shuxingvalue = MyHelp.SubPropModel(propsLog, selectSuitItem);
        }
    }
}
